﻿@using TrainingManagerSystem.WebUI.Models
@model TrainingManagerSystem.WebUI.Models.AccountViewModel

<link href="~/Content/Css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/Content/Css/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
<div id="body">
    <div id="content-left" class="float-left">
        <div class="title-nav">
            Department
        </div>
        <div id='treeWrapper'>
            @Html.RenderTree((IEnumerable<CompositeThing>)ViewBag.Data, t => t.Name)
        </div>
    </div>

    <div id="content-right">

        <div class="title-view bold">View Account</div>

        <form action="/" method="post">
            <div class="div-search">
                <table width="100%">
                    <tr>
                        <td class="label">Account Name</td>
                        <td class="control-field">
                            <input type="text" id="txtAccountName" /></td>
                        <td class="label">Full Name</td>
                        <td class="control-field">
                            <input type="text" id="txtFullName"/></td>
                    </tr>
                    <tr>
                        <td class="label">Contract Type</td>
                        <td>
                        @Html.DropDownList("ddlContractType", Model.ContractTypes, "All")
                        <td class="label">Location</td>
                        <td>
                            @Html.DropDownList("ddlLocation", Model.Locations, "All")
                        </td>
                    </tr>
                    <tr>
                        <td class="label">Employee ID</td>
                        <td>
                            <input type="text" id="txtEmployeeId"/>
                        </td>
                        <td class="label">Job Title</td>
                        <td>
                            @Html.DropDownList("ddlJobTitle", Model.JobTitles, "All")
                        </td>
                    </tr>
                    <tr>
                        <td class="label">Status</td>
                        <td>
                        @Html.DropDownList("ddlStatus", Model.Statuses, "All")
                        <td class="label">Experience</td>
                        <td>
                            <input type="text" class="experienceStart" id="txtExStart"/>
                            >> 
                            <input type="text" class="experienceEnd" id="txtExEnd"/>
                            (Months)
                        </td>
                    </tr>
                </table>

            </div>
            <div class="float-right">
                <button type="submit" class="btn" id="btnSearch">
                    <span class="i-invertedSearchLoupe">SEARCH</span>
                </button>
            </div>
        </form>
        <div class='clear-fix'><span id='setting'>Table configuration</span></div>
        <div id="list-search">
            <table width="100%" class="sortable" id="dataTables">
                <thead>
                    <tr>
                        <th>Employee ID</th>
                        <th>Account Name</th>
                        <th>Full Name</th>
                        <th>Mobile Phone</th>
                        <th>Department</th>
                        <th>Contract Type</th>
                        <th>Officer Code</th>
                        <th>Birth Of Date</th>
                        <th>Location</th>
                        <th>Role</th>
                        <th>Level</th>
                        <th>Rank</th>
                        <th>Job Title</th>
                        <th>Job Function</th>
                        <th>Hire Date</th>
                        <th>Termination Date</th>
                        <th>Address</th>
                        <th>Experience</th>
                        <th>Account Status</th>
                        <th>Descriptions</th>
                        <th style="display: none;"></th>
                    </tr>
                </thead>
                <tfoot></tfoot>
                <tbody>
                    @foreach(var account in Model.Accounts) {
                        <tr>
                            <td>@account.EmployeeId</td>
                            <td><a class="acc" href="#" data-employeeId="@account.EmployeeId">@account.AccountName</a></td>
                            <td>@account.FullName</td>
                            <td class="text-right">@account.MobilePhone</td>
                            <td>@account.Department.DepartmentName</td>
                            <td>@account.ContractType.ContractTypeName</td>
                            <td>@account.OfficerCode.OfficerCodeName</td>
                            <td class="text-right">@if (account.BOD != null) {
                                                       @account.BOD.Value.ToString("dd-MMM-yyyy")
                                                   }
                            </td>
                            <td>@account.Location.LocationName</td>
                            <td>@account.Role.RoleName</td>
                            <td>@account.Level.LevelName</td>
                            <td class="text-right">@account.Rank.RankName</td>
                            <td>@account.JobTitle.JobTitleName</td>
                            <td>@account.JobFunction.JobFunctionName</td>
                            <td class="text-right">@if (account.HireDate != null) {
                                                       @account.HireDate.Value.ToString("dd-MMM-yyyy")
                                                   }
                            </td>
                            <td class="text-right">@if (account.OutOfDate != null) {
                                                       @account.OutOfDate.Value.ToString("dd-MMM-yyyy")
                                                   }
                            </td>
                            <td>@account.Address</td>
                            <td class="text-right">@account.Month</td>
                            <td>@account.StatusAccount.StatusAccountName</td>
                            <td>@account.Descriptions</td>
                            <td style="display: none;">@account.TotalRows</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        <div class="clear-fix"></div>

        <div id="details">
        </div>
        <div id='pop'>
            <div class='acTitle title-view'>Selected Fields</div>
            <table id='selectedFileds'>
                <tr><td><input type='checkbox' id='selectAll'/> Select all</td></tr>
                <tr>
                    <td><input type='checkbox' checked='checked' class='fields'/> Employee ID</td><td><input type='checkbox' checked='checked' class='fields'/> Account Name</td><td><input type='checkbox' checked='checked' class='fields'/> Full Name</td><td><input type='checkbox' class='fields'/> Mobile Phone</td>
                </tr>
                <tr>
                    <td><input type='checkbox' checked='checked' class='fields'/> Department</td><td><input type='checkbox' checked='checked' class='fields'/> Contract Type</td><td><input type='checkbox' checked='checked' class='fields'/> Officer Code</td><td><input type='checkbox' class='fields'/> Birth Of Date</td>
                </tr>
                <tr>
                    <td><input type='checkbox' class='fields'/> Location</td><td><input type='checkbox' class='fields'/> Role</td><td><input type='checkbox' class='fields'/> Level</td><td><input type='checkbox' class='fields'/> Rank</td>
                </tr>
                <tr>
                    <td><input type='checkbox' class='fields'/> Job Title</td><td><input type='checkbox' class='fields'/> Job Function</td><td><input type='checkbox' class='fields'/> Hire Date</td><td><input type='checkbox' class='fields'/> Termination Date</td>
                </tr>
                <tr>
                    <td><input type='checkbox' class='fields'/> Address</td><td><input type='checkbox' class='fields'/> Experience</td><td><input type='checkbox' class='fields'/> Account Status</td><td><input type='checkbox' class='fields'/> Descriptions</td>
                </tr>
            </table>
            <div class='btns'><input type='button' value='Cancel' id='cancelBtn'/><input type='button' value='Accept' id='changeFields'/></div>
        </div>
        <div class="clear-fix"></div>
    </div>
    <div class="clear-fix"></div>
</div>
@section scripts {
    <script src="~/Content/Scripts/jquery-ui-tabs.js"></script>
    <script src="~/Content/Scripts/convertDatetimeJson.js"></script>
    <script src="~/Content/Scripts/jquery.commonFunctions.js"></script>

    <script type="text/javascript">
        //Create Tree Menu 
        function CreateTreeMenuById(id) {
            $('#' + id).treeview({
                collapsed: true,
                animated: "fast",
                prerendered: true,
                persist: "location"
            });

            $("#" + id + " li ul li a").click(function () {
                $('#all').removeClass('selected');
                $("#" + id + " li span").removeClass("selected");
                $("#" + id + " li ul li a").removeClass("selected");
                $("#" + id + " li a").removeClass("selected");
                $(this).addClass("selected");
            });

            $("#" + id + " li ul li a").click(function () {
                $('#all').removeClass('selected');
                $("#" + id + " li span").removeClass("selected");
                $("#" + id + " li ul li a").removeClass("selected");
                $("#" + id + " li a").removeClass("selected");
                $(this).addClass("selected");
            });

            $("#" + id + " span").click(function () {
                $('#all').removeClass('selected');
                $("#tree span").removeClass("selected");
                $("#tree li ul li a").removeClass("selected");
                $("#" + id + " li a").removeClass("selected");
                $(this).addClass("selected");
            });

            $("#" + id + " li a").click(function () {
                $('#all').removeClass('selected');
                $("#" + id + " li a").removeClass("selected");
                $("#tree span").removeClass("selected");
                $("#tree li ul li a").removeClass("selected");
                $(this).addClass("selected");
            });
        }

        function PrepareTree() {

            $('#treeWrapper').prepend('<div class="hitarea expandable-hitarea"><span id="all" style="cursor:pointer">All</span></div>');
            $('#all').click(function () {
                $('#tree a').removeClass('selected');
                $(this).addClass('selected');
                departmentId = 0;
                getDataFromDatabase('dataTables', 1, $('#dataTables_length option:selected').text());
            });
            var uls = $('#treeWrapper li:has(ul)');
            uls.each(function () {
                $(this).prepend('<div class="hitarea expandable-hitarea"></div>');
            });
            var a = $('#treeWrapper li:has(ul) a');
            a.each(function () {
                $(this).replaceWith('<span onclick="getTreeViewDataClick(this)">' + $(this).html() + '</span>');
            });
            var obj = $('#treeWrapper ul:first');
            obj.attr('id', 'tree');
            obj.removeClass('hidden');
            obj.addClass('treeview');
            setIdDepartment($('#treeWrapper li a'));
            setIdDepartment($('#treeWrapper li span'));
        }

        var departmentId = 0;
        //Get departmentId
        function getTreeViewDataClick(sender) {
            departmentId = sender.id;
        }

        function setIdDepartment(obj) {
            obj.each(function () {
                var val = $(this).text();
                var n = val.length;
                while (n > 0) {
                    if (val[n] == '_') {
                        break;
                    }
                    n--;
                }
                $(this).attr('id', val.substring(n + 1, val.length));
                $(this).text(val.substring(0, n));
                $(this).click(function () {
                    getDataFromDatabase('dataTables', 1, 20);
                });
            });
        }

        //Create Datatable 
        function CreateDataTableById(id, columns, wrapper) {
            var cols = [];
            var arr = columns.split(',');
            for (var i = 0; i < arr.length; i++) {
                cols.push({
                    "aTargets": [parseInt(arr[i])],
                    "bVisible": false
                });
            }

            var obj = $("#" + id).dataTable(
                {
                    "sDom": '<"wrapper"tpli>',
                    "aLengthMenu": [[20, 50, 100, -1], [20, 50, 100, "All"]],
                    "iDisplayLength": 20,
                    "sPaginationType": "full_numbers",
                    "aaSorting": [[0, "asc"]],
                    "aoColumnDefs": cols,
                    "bDestroy": true
                });
            $('.' + wrapper).addClass('configurationPaging');
            return obj;
        }

        //Hidden columns: hideColumns is list of columns which will hide : '1,4,6'
        function ChangeTableConfiguration(senderId, tableId, columns, wrapper, popId) {
            $('#' + senderId).click(function () {
                hidden = getColumnsHide(columns);
                CreateDataTableById(tableId, hidden, wrapper);
                $('#' + popId).bPopup().close();
            });
        }

        //get list of columns will hide ( not checked )
        function getColumnsHide(className) {
            var hidden = '';
            $('.' + className).each(function (i) {
                if ($(this).prop('checked') == false) {
                    hidden += i + ',';
                }
            });
            hidden += '20 '; //must has a space
            return hidden.substring(0, hidden.length - 1);
        }

        var isSelectAll = false;
        function Initial() {
            $('#selectAll').click(function () {
                isSelectAll = !isSelectAll;
                if (isSelectAll) {
                    $('.fields').each(function () {
                        $(this).attr('checked', 'checked');
                    });
                } else {
                    $('.fields').each(function () {
                        $(this).attr('checked', false);
                    });
                }
            });
            $('#pop').hide();
            $('#details').hide();
            //Show table configuration setting
            $('#setting').click(function () {
                $('#pop').bPopup();
            });
            //Close table configuration
            $('#cancelBtn').click(function () {
                $('#pop').bPopup().close();
            });
            //Add class selected for node All in tree view
            $('#all').addClass('selected');
        }

        function getDataFromDatabase(idTable, pageNumber, pageSize) {
            $.ajax({
                url: '@Url.Action("SearchAjax")',
                type: 'POST',
                data: {
                    accountName: $('#txtAccountName').val(),
                    fullName: $('#txtFullName').val(),
                    locationId: $('#ddlLocation').val(),
                    jobTitleId: $('#ddlJobTitle').val(),
                    employeeId: $('#txtEmployeeId').val(),
                    departmentId: departmentId,
                    contractTypeId: $('#ddlContractType').val(),
                    statusAccountId: $('#ddlStatus').val(),
                    minMonth: $('#txtExStart').val(),
                    maxMonth: $('#txtExEnd').val(),
                    pageNumber: pageNumber,
                    pageSize: pageSize
                },
                dataType: 'JSON',
                success: function (data) {
                    var old = null;
                    if (objTable.fnGetData(0) != null) {
                        old = objTable.fnGetData(0)[20];
                    }
                    window.objTable.fnClearTable();
                    for (var i = 0; i < data.length; i++) {
                        window.objTable.fnAddData([
                            data[i].EmployeeId,
                            '<a class="acc" href="javascript:;" data-employeeId="' + data[i].EmployeeId + '">' + data[i].AccountName + '</a>',
                            data[i].FullName,
                            data[i].MobilePhone,
                            data[i].Department.DepartmentName,
                            data[i].ContractType.ContractTypeName,
                            data[i].OfficerCode.OfficerCodeName,
                            formatJSONDate(data[i].BOD),
                            data[i].Location.LocationName,
                            data[i].Role.RoleName,
                            data[i].Level.LevelName,
                            data[i].Rank.RankName,
                            data[i].JobTitle.JobTitleName,
                            data[i].JobFunction.JobFunctionName,
                            formatJSONDate(data[i].HireDate),
                            formatJSONDate(data[i].OutOfDate),
                            data[i].Address,
                            data[i].Month,
                            data[i].StatusAccount.StatusAccountName,
                            data[i].Descriptions,
                            data[i].TotalRows
                        ]);
                    }

                    if (objTable.fnGetData(0)[20] != old) {
                        configurationPaging('dataTables', 0, $('#dataTables_length option:selected').text(), objTable.fnGetData(0)[20]);
                    }
                    //ShowPopupByAccoutName('dataTables', 'details', 'notes');
                    $(".acc").on("click", function () {
                        var employeeId = $(this).attr('data-employeeId');
                        ShowPopupAccountDetails(employeeId);
                    });
                    
                    showTotalRecords(idTable, pageNumber - 1, pageSize, objTable.fnGetData(0)[20]);
                },
                error: function () {
                    alert('Error!');
                }
            });
        }

        function ShowPopupAccountDetails(employeeId) {
            $.ajax({
                url: '@Url.Action("GetAccountDetails")',
                type: 'POST',
                data: { employeeId: employeeId },
                dataType: 'JSON',
                success: function (data) {
                    $('#details').empty();
                    var html = "<div class='acTitle'>Account Details</div>";
                    html += "<div><table width='100%' style='margin: 15px;'>";
                    html += "<tr><td class='label bold twentyFivePercent'>Employee ID: </td>";
                    html += "<td class='twentyFivePercent'>" + data.EmployeeId + "</td>";
                    html += "<td class='label bold twentyFivePercent'>Department: </td>";
                    html += "<td class='twentyFivePercent'>" + data.Department.DepartmentName + "</td></tr>";
                    html += "<tr><td class='label bold'>Account Name: </td><td>" + data.AccountName + "</td>";
                    html += "<td class='label bold'>Location: </td><td>" + data.Location.LocationName + "</td></tr>";
                    html += "<tr><td class='label bold'>Full Name: </td><td>" + data.FullName + "</td>";
                    html += "<td class='label bold'>Job Title: </td><td>" + data.JobTitle.JobTitleName + "</td></tr>";
                    html += "<tr><td class='label bold'>Mobile Phone: </td><td>" + data.MobilePhone + "</td>";
                    html += "<td class='label bold'>Termination Date: </td><td>";
                    html += formatJSONDate(data.OutOfDate);
                    html += "</td></tr></table>";

                    html += "<div id='tabs'><ul><li><a href='#tabs-1'>General</a></li><li><a href='#tabs-2'>Skill</a></li><li><a href='#tabs-3'>Course</a></li><li><a href='#tabs-4'>Certificate</a></li><li><a href='#tabs-5'>Language Scores</a></li></ul>";
                    html += "<div id='tabs-1'><table width='100%'><tr>";
                    html += "<td class='label bold twentyFivePercent'>Contract Type</td><td class='twentyFivePercent'>" + data.ContractType.ContractTypeName + "</td>";
                    html += "<td class='label bold twentyFivePercent'>Address</td><td class='twentyFivePercent'>" + data.Address + "</td></tr>";
                    html += "<tr><td class='label bold'>Level</td><td>" + data.Level.LevelName + "</td>";
                    html += "<td class='label bold'>Rank</td><td>" + data.Rank.RankName + "</td></tr>";
                    html += "<tr><td class='label bold'>Status Account</td><td>" + data.StatusAccount.StatusAccountName + "</td>";
                    html += "<td class='label bold'>Hire Date</td><td>";
                    html += formatJSONDate(data.HireDate);
                    html += "</td></tr>";
                    html += "<tr><td class='label bold'>Role</td><td>" + data.Role.RoleName + "</td>";
                    html += "<td class='label bold'>Birth Of Date</td><td>";
                    html += formatJSONDate(data.BOD);
                    html += "</td></tr>";
                    html += "<tr><td class='label bold'>Officer Code</td><td>" + data.OfficerCode.OfficerCodeName + "</td>";
                    html += "<td class='label bold'>Job Function</td><td>" + data.JobFunction.JobFunctionName + "</td></tr>";
                    html += "<tr><td class='label bold'>Description</td><td colspan='3'>" + data.Descriptions + "</td></tr>";
                    html += "</table></div>";

                    html += "<div id='tabs-2' class='popup-overflow'><table class='popup-tables' width='100%'><tr><th>Skill Name</th><th>Description</th></tr>";
                    for (var i = 0; i < data.AccountSkills.length; i++) {
                        html += "<tr><td>" + data.AccountSkills[i].Skill.SkillName + "</td>";
                        html += "<td>" + data.AccountSkills[i].Skill.Descriptions + "</td></tr>";
                    }
                    html += "</table></div>";

                    html += "<div id='tabs-3' class='popup-overflow'><table class='popup-tables'><tr><th>Course</th><th>Time Commit</th><th>End Date</th><th>Costs</th><th>Refunds</th><th>Currency</th></tr>";
                    for (i = 0; i < data.CourseRefunds.length; i++) {
                        html += "<tr><td>" + data.CourseRefunds[i].Course + "</td>";
                        html += "<td class='text-right'>" + data.CourseRefunds[i].TimeCommit + "</td>";
                        html += "<td class='text-right'>";
                        html += formatJSONDate(data.CourseRefunds[i].EndDate);
                        html += "</td>";
                        html += "<td class='text-right'>" + data.CourseRefunds[i].Costs + "</td>";
                        html += "<td class='text-right'>" + data.CourseRefunds[i].Refunds + "</td>";
                        html += "<td class='text-right'>" + data.CourseRefunds[i].Currency + "</td></tr>";
                    }
                    html += "</table></div>";

                    html += "<div id='tabs-4' class='popup-overflow'><table class='popup-tables'><tr><th>Certificate</th><th>Time Commit</th><th>Completed Date</th><th>Fee</th><th>Refunds</th><th>Currency</th></tr>";
                    for (i = 0; i < data.CertificateRefunds.length; i++) {
                        html += "<tr><td>" + data.CertificateRefunds[i].Certificate + "</td>";
                        html += "<td class='text-right'>" + data.CertificateRefunds[i].TimeCommit + "</td>";
                        html += "<td class='text-right'>";
                        html += formatJSONDate(data.CertificateRefunds[i].CompleteDate);
                        html += "</td>";
                        html += "<td class='text-right'>" + data.CertificateRefunds[i].Fee + "</td>";
                        html += "<td class='text-right'>" + data.CertificateRefunds[i].Refunds + "</td>";
                        html += "<td class='text-right'>" + data.CertificateRefunds[i].Currency + "</td></tr>";
                    }
                    html += "</table></div>";

                    html += "<div id='tabs-5' class='popup-overflow'><table class='popup-tables'><tr><th>Date</th><th>Language Name</th><th>Score</th><th>Note</th></tr>";
                    for (i = 0; i < data.LanguageScores.length; i++) {
                        html += "<tr><td>" + formatJSONDate(data.LanguageScores[i].Date) + "</td>";
                        html += "<td>" + data.LanguageScores[i].LanguageName + "</td>";
                        html += "<td>" + data.LanguageScores[i].Score + "</td>";
                        html += "<td>" + data.LanguageScores[i].Note + "</td></tr>";
                    }
                    html += "</table></div>";

                    html += "</div>";
                    $('#details').html(html);
                    $("#tabs").tabs({
                        "show": function (event, ui) {
                            var table = $.fn.dataTable.fnTables(true);
                            if (table.length > 0) {
                                $(table).dataTable().fnAdjustColumnSizing();
                            }
                        }
                    });
                    $('#details').bPopup();
                },
                error: function () {
                    alert('Error!');
                }
            });
        };
        
        var objTable;
        var hidden = '';
        $(document).ready(function () {
            PrepareTree();
            CreateTreeMenuById('tree');
            Initial();
            window.hidden = getColumnsHide('fields');
            window.objTable = CreateDataTableById('dataTables', window.hidden);            
            ChangeTableConfiguration('changeFields', 'dataTables', 'fields', 'wrapper', 'pop', 0, $('#dataTables_length option:selected').text(), objTable.fnGetData(0)[20]);
            
            $('.wrapper').addClass('configurationPaging');
            configurationPaging('dataTables', 0, $('#dataTables_length option:selected').text(), objTable.fnGetData(0)[20]);
            
            $('#btnSearch').on("click", function (e) {
                e.preventDefault();
                getDataFromDatabase('dataTables', 1, $('#dataTables_length option:selected').text());
            });

            $('#btnCloseI').click(function () {
                $('#details').bPopup().close();
            });

            $(".acc").click(function() {
                var employeeId = $(this).attr('data-employeeId');
                ShowPopupAccountDetails(employeeId);
            });

            $('#cancelBtn').click(function () {
                $('#pop').bPopup().close();
            });
            $('#pop').hide();
            $('#details').hide();

            $("#table-result").dataTable(
                {
                    "sDom": '<"wrapper"tpli>',
                    "aLengthMenu": [[20, 50, 100, -1], [20, 50, 100, "All"]],
                    "iDisplayLength": 20,
                    "sPaginationType": "full_numbers",
                    "aaSorting": [[0, "asc"]]
                });
            $('.wrapper').addClass('configurationPaging');
            $('#pop').hide();
            $('#changeFields').click(function () {
                $('#table-result').dataTable({
                    "aoColumnDefs": [
                        { "bVisible": false, "aTargets": [0] },
                        { "bVisible": false, "aTargets": [10] },
                        { "bVisible": false, "aTargets": [11] },
                        { "bVisible": false, "aTargets": [12] },
                        { "bVisible": false, "aTargets": [13] },
                        { "bVisible": false, "aTargets": [14] }],
                    "sDom": '<"wrapper"tpli>',
                    "aLengthMenu": [[20, 50, 100, -1], [20, 50, 100, "All"]],
                    "iDisplayLength": 20,
                    "sPaginationType": "full_numbers",
                    "aaSorting": [[0, "asc"]],
                    "bDestroy": true
                }).fnDraw();
                $('#pop').bPopup().close();
            });
            $('#setting').click(function () {
                $('#pop').bPopup();
            });
            $('.wrapper').addClass('configurationPaging');

        });
    </script>
}
